import { API_BASE_URL, REQUEST_TIMEOUT, RESPONSE_CODE } from '../config/index.js'

// 获取token的辅助函数
const getTokenFromStorage = () => {
  const TOKEN_KEY = 'satoken'
  const TOKEN_EXPIRE_KEY = 'satoken_expire'
  
  // 从localStorage获取token
  const token = localStorage.getItem(TOKEN_KEY) || ''
  
  // 检查token是否过期
  const expireTime = localStorage.getItem(TOKEN_EXPIRE_KEY)
  if (expireTime && Date.now() > parseInt(expireTime)) {
    console.log('检测到token已过期，清除token')
    localStorage.removeItem(TOKEN_KEY)
    localStorage.removeItem(TOKEN_EXPIRE_KEY)
    return ''
  }
  
  return token
}

// 统一的请求方法
const request = async (url, options = {}) => {
  try {
    // 1. 添加基础 URL
    const fullUrl = url.startsWith('http') ? url : `${API_BASE_URL}${url}`
    
    // 2. 设置默认请求头
    const defaultHeaders = {
      'Content-Type': 'application/json',
    }
    
    // 3. 获取token并添加到请求头
    const currentToken = getTokenFromStorage()
    if (currentToken) {
      // SaToken配置的token名称是'token'，不是标准的'Authorization'
      defaultHeaders['token'] = currentToken
      console.log('请求携带token:', currentToken.substring(0, 20) + '...')
    } else {
      console.log('请求未携带token')
    }
    
    // 4. 合并选项
    const requestOptions = {
      ...options,
      headers: {
        ...defaultHeaders,
        ...options.headers,
      },
      timeout: REQUEST_TIMEOUT,
    }
    
    console.log('发送请求:', fullUrl, requestOptions.method)
    
    // 4. 发送请求 - 简化版本，先确保能发出请求
    const response = await fetch(fullUrl, requestOptions)
    
    console.log('请求响应状态:', response.status)
    
    // 5. 拦截器处理响应
    return await handleResponse(response)
    
  } catch (error) {
    // 6. 拦截器处理错误
    console.error('请求异常:', error)
    return handleError(error)
  }
}

// 处理响应
const handleResponse = async (response) => {
  // 检查HTTP状态码
  if (!response.ok) {
    // 如果是401未授权，需要特殊处理
    if (response.status === 401) {
      console.log('检测到401未授权，跳转到登录页')
      // 清除本地token
      const TOKEN_KEY = 'satoken'
      const TOKEN_EXPIRE_KEY = 'satoken_expire'
      localStorage.removeItem(TOKEN_KEY)
      localStorage.removeItem(TOKEN_EXPIRE_KEY)
      // 跳转到登录页
      window.location.href = '/login'
      throw new Error('登录已过期，请重新登录')
    }
    throw new Error(`HTTP error! status: ${response.status}`)
  }
  
  // 解析响应数据
  const result = await response.json()
  
  // 根据状态码进行拦截处理
  switch (result.code) {
    case RESPONSE_CODE.SUCCESS:
      // 成功响应，直接返回数据
      return {
        success: true,
        data: result.data,
        message: result.msg || '操作成功'
      }
      
    case RESPONSE_CODE.UNAUTHORIZED:
      // 未授权，清除token并跳转到登录页
      console.log('检测到401未授权，跳转到登录页')
      const TOKEN_KEY = 'satoken'
      const TOKEN_EXPIRE_KEY = 'satoken_expire'
      localStorage.removeItem(TOKEN_KEY)
      localStorage.removeItem(TOKEN_EXPIRE_KEY)
      // 跳转到登录页
      window.location.href = '/login'
      throw new Error('登录已过期，请重新登录')
      
    default:
      // 其他错误
      return {
        success: false,
        message: result.msg || '请求失败',
        code: result.code
      }
  }
}

// 处理错误
const handleError = (error) => {
  console.error('请求失败:', error)
  
  if (error.name === 'AbortError') {
    return {
      success: false,
      message: '请求超时，请检查网络连接'
    }
  }
  
  return {
    success: false,
    message: '网络错误，请检查网络连接'
  }
}

// 便捷的请求方法
export const get = (url, options = {}) => {
  return request(url, { ...options, method: 'GET' })
}

export const post = (url, data, options = {}) => {
  return request(url, { 
    ...options, 
    method: 'POST', 
    body: JSON.stringify(data) 
  })
}

export const put = (url, data, options = {}) => {
  return request(url, { 
    ...options, 
    method: 'PUT', 
    body: JSON.stringify(data) 
  })
}

export const del = (url, options = {}) => {
  return request(url, { ...options, method: 'DELETE' })
}

export default request